import {
	getUserInfo
} from "../../api/user.js";
import {
	LOGIN_STATUS,
	UID
} from '../../config/cache';
import Cache from '../../utils/cache';
import {
	USER_INFO
} from '../../config/cache';

const state = {
	token: Cache.get(LOGIN_STATUS) || null,
	backgroundColor: "#fff",
	userInfo: null,
	uid: Cache.get(UID) || null,
	homeActive: false,
	chatUrl: Cache.get('chatUrl') || '',
	
	orderType: 'takein',
	address: {
		"id": 1,
		"user_id": 1,
		"name": "小明先生",
		"houseName":"环球中心",
		"houseId":"3",
		"phone": "18666610100",
		"gender": 0,
		"addr": "成都高新区锦城路",
		"complete_address": "成都环球中心111号",
		"description": "ABC1234",
		"latitude": "",
		"longitude": "",
		"is_default": 1,
	},
	member: {},
	remark: '不打包'
};

const mutations = {
	LOGIN(state, opt) {
		state.token = opt.token;
		Cache.set(LOGIN_STATUS, opt.token, opt.time);
	},
	SET_MEMBER(state, member) {
		state.member = member
	},
	SETUID(state,val){
		state.uid = val;
		Cache.set(UID, val);
	},
	UPDATE_LOGIN(state, token) {
		state.token = token;
	},
	LOGOUT(state) {
		state.token = undefined;
		state.uid = undefined
		Cache.clear(LOGIN_STATUS);
		Cache.clear(UID);
	},
	BACKGROUND_COLOR(state, color) {
		state.color = color;
		document.body.style.backgroundColor = color;
	},
	UPDATE_USERINFO(state, userInfo) {
		state.userInfo = userInfo;
	},
	OPEN_HOME(state) {
		state.homeActive = true;
	},
	CLOSE_HOME(state) {
		state.homeActive = false;
	},
	SET_CHATURL(state, chatUrl){
		state.chatUrl = chatUrl;
	},
	
	SET_ORDER_TYPE(state, orderType) {
		state.orderType = orderType
	},
	SET_ADDRESS(state, address) {
		console.log(address)
		state.address = address
	},
	SET_REMARK(state, remark) {
		state.remark = remark
	}
};

const actions = {
	USERINFO({
		state,
		commit
	}, force) {
		if (state.userInfo !== null && !force)
			return Promise.resolve(state.userInfo);
		else
			return new Promise(reslove => {
				getUserInfo().then(res => {
					commit("UPDATE_USERINFO", res.data);
					Cache.set(USER_INFO, res.data);
					reslove(res.data);
				});
			}).catch(() => {

			});
	}
};

export default {
	state,
	mutations,
	actions
};
